/*
 * @Author: 肖思汗 
 * @Date: 2025-06-10 11:52:14 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-06-16 20:20:51
 */

import { autorun, makeAutoObservable } from "mobx";
import addressManageApi from "./addressManageApi";
import userStore from "src/pages/User/userStore";
import { ReceiveAddress } from "types/type";

// 收货地址管理
class AddressManageStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });

        autorun(() => {
            if (userStore.isLogin) {
                this.getList();
            }
        });

    }

    // 选择模式
    selectMode = false;
    setSelectMode(selectMode: boolean) {
        this.selectMode = selectMode;
    }

    // 选择的地址id
    selectedAddressId: number = 0;//选择的地址id
    setSelectedAddressId(selectedAddressId: number) {
        this.selectedAddressId = selectedAddressId;
    }

    page: number = 1;//当前页面
    pageSize: number = 9999;//分页数
    total: number = 0;//总数
    list: Array<ReceiveAddress> = [];//收货地址列表
    hasMore: boolean = true;//是否有更多数据

    //获取数据
    getList(page: number = this.page, pageSize: number = this.pageSize) {
        this.page = page;
        this.pageSize = pageSize;

        return addressManageApi.getlistMyAddress().then((res: any) => {
            this.list = res.rows;
            if (this.list.length > 0 && this.selectedAddressId === 0) {
                this.selectedAddressId = this.list[0].appAddressId;
            }

            this.total = res.total;
            this.hasMore = res.rows.length === this.pageSize;
        });
    }

    //新增数据
    add(data: Omit<ReceiveAddress, "appAddressId">) {
        return addressManageApi.add(data).then(() => {
            this.getList();
        });
    }

    //删除数据
    delete(addressId: number | string) {
        return addressManageApi.delete(addressId).then(() => {
            this.getList();
        });
    }

    //更新数据
    updata(data: ReceiveAddress) {
        return addressManageApi.update(data).then(() => {
            this.getList();
        });
    }

}

const addressManageStore = new AddressManageStore();

export default addressManageStore;